<?php

/**
   reserved parameters names:
      method      mandatory
      forward     URL to forward (return variable name can be included e.g. page.php?id=$return) or 'referer'
      return      name of return variable in forward
*/

if (isset($argv)) exit;    //dont't call from command line

require_once 'config.php';
require_once 'param.php';
require_once 'user.php';

$user = \cf\User::getLoggedIn();


function params2MethodArgs($method, $params)
{
   $funcInfo = new ReflectionFunction($method);

   $args = array();
   foreach ($funcInfo->getParameters() as $paramInfo)
   {
      $nm = $paramInfo->getName();
      $val = null;

      if (!array_key_exists($nm,$params))
      {
         if ($paramInfo->isDefaultValueAvailable()) {
            $val = $paramInfo->getDefaultValue();
         }

         if (is_null($val) && !$paramInfo->isOptional()) {
            throw new Exception("Parameter [$nm] of [$method] can not be null");
         }
      }
      else 
      {
         $val = $params[$nm];
      }

      $classInfo = $paramInfo->getClass();
      if ($classInfo) {
         $val = eval("return new ".$classInfo->getName()."('$val');");
      }

      $args[] = $val;
   }
   return $args;
}


try 
{
   list($module,$method) = explode('.',cf\param::get('method'));

   require_once \cf\Config::path."api/$module.php";
   
   $method = "cf\\api\\$module\\$method";
   
   if (!function_exists($method))
   {
      throw new Exception("Invalid method - $method");
   }

   $returnHTML = false;
   $res = call_user_func_array($method, params2MethodArgs($method, cf\param::toArray()));

   if (cf\param::exist('return'))             
   {                                       
      $retVarName = cf\param::get('return');  
      $$retVarName = $res;                 
   }                                       

   if (cf\param::exist('forward')) 
   {
      $url = cf\param::get('forward');
      if ('referer' == $url) {
         $url = $_SERVER['HTTP_REFERER'];
      }
      else {
         eval('$url="'.$url.'";');
      }
      forward($url);
   }

	if (!$returnHTML) {
		header('Content-Type: application/json');
		$res = json_encode($res);
	}
	echo $res;
}
catch (Exception $e)
{
   header("HTTP/1.0 500 Error occured");
   echo $e;
}

?>